<template>
  <div class="flex flex-col gap-4">
    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-2 mb-6">
      <div>
        <h1 class="text-3xl font-bold tracking-tight">仪表盘</h1>
        <p class="text-muted-foreground">欢迎使用Mocige管理后台。查看系统概览和关键指标。</p>
      </div>
      <div class="flex gap-2">
        <Button variant="outline" size="sm" @click="fetchStats('today')">
          <Clock class="mr-2 h-4 w-4" />
          今日
        </Button>
        <Button variant="outline" size="sm" @click="fetchStats('week')">
          本周
        </Button>
        <Button variant="outline" size="sm" @click="fetchStats('month')">
          本月
        </Button>
        <Button variant="outline" size="sm" @click="fetchStats('all')">
          全部
        </Button>
      </div>
    </div>

    <div v-if="loading" class="flex justify-center items-center h-64">
      <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
    </div>

    <div v-else class="flex flex-col gap-4">
      <div class="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <DashboardCard
            v-for="stat in stats"
            :key="stat.id"
            :title="stat.name"
            :value="stat.value"
            :change="stat.change"
            :trend="stat.changeType"
            :icon="stat.icon"
        />
      </div>

      <Tabs default-value="overview" class="space-y-4">
        <TabsList>
          <TabsTrigger value="overview">概览</TabsTrigger>
          <TabsTrigger value="analytics">分析</TabsTrigger>
          <TabsTrigger value="activity">最近活动</TabsTrigger>
        </TabsList>

        <TabsContent value="overview" class="space-y-4">
          <div class="grid gap-4 md:grid-cols-2 lg:grid-cols-7">
            <Card class="col-span-4">
              <CardHeader>
                <CardTitle>用户增长</CardTitle>
                <CardDescription>用户数量随时间变化</CardDescription>
              </CardHeader>
              <CardContent class="h-[300px] flex items-center justify-center border-t pt-4">
                <div class="text-sm text-muted-foreground">用户增长图表占位符</div>
              </CardContent>
            </Card>
            <Card class="col-span-3">
              <CardHeader>
                <CardTitle>学习统计</CardTitle>
                <CardDescription>已学单词数量与复习率</CardDescription>
              </CardHeader>
              <CardContent class="h-[300px] flex items-center justify-center border-t pt-4">
                <div class="text-sm text-muted-foreground">学习统计图表占位符</div>
              </CardContent>
            </Card>
          </div>

          <div class="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
            <Card class="col-span-2">
              <CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
                <div class="space-y-1">
                  <CardTitle>最近注册用户</CardTitle>
                  <CardDescription>最近加入平台的用户</CardDescription>
                </div>
                <router-link to="/users">
                  <Button variant="outline" size="sm">
                    查看全部
                  </Button>
                </router-link>
              </CardHeader>
              <CardContent>
                <div class="space-y-8">
                  <div v-for="user in recentUsers" :key="user.id" class="flex items-center">
                    <div class="mr-4 rounded-full bg-primary/10 p-2">
                      <User class="h-4 w-4 text-primary" />
                    </div>
                    <div class="space-y-1">
                      <p class="text-sm font-medium leading-none">{{ user.email }}</p>
                      <p class="text-sm text-muted-foreground">注册于 {{ formatDate(user.createdAt) }}</p>
                    </div>
                    <div class="ml-auto font-medium">{{ user.isActive ? '活跃' : '非活跃' }}</div>
                  </div>
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
                <div class="space-y-1">
                  <CardTitle>热门单词</CardTitle>
                  <CardDescription>本周最多复习的单词</CardDescription>
                </div>
                <router-link to="/words">
                  <Button variant="outline" size="sm">
                    查看全部
                  </Button>
                </router-link>
              </CardHeader>
              <CardContent>
                <div class="space-y-8">
                  <div v-for="(word, index) in popularWords" :key="word.id" class="flex items-center">
                    <div class="mr-4 rounded-full bg-primary/10 p-2">
                      <BookOpen class="h-4 w-4 text-primary" />
                    </div>
                    <div class="space-y-1">
                      <p class="text-sm font-medium leading-none">{{ word.word }}</p>
                      <p class="text-sm text-muted-foreground">{{ word.reviewCount }} 次复习</p>
                    </div>
                    <div class="ml-auto font-medium">{{ word.masteryRate }}% 掌握度</div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          <div class="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
            <Card>
              <CardHeader class="pb-2">
                <CardTitle class="text-sm font-medium">测试完成率</CardTitle>
              </CardHeader>
              <CardContent>
                <div class="text-2xl font-bold">{{ quizCompletionRate }}%</div>
                <div class="mt-4 h-2 w-full rounded-full bg-muted">
                  <div class="h-2 rounded-full bg-primary" :style="{ width: quizCompletionRate + '%' }"></div>
                </div>
                <div class="mt-2 text-xs text-muted-foreground">{{ quizCompletionChange }} 相比上周</div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader class="pb-2">
                <CardTitle class="text-sm font-medium">平均学习时间</CardTitle>
              </CardHeader>
              <CardContent>
                <div class="text-2xl font-bold">{{ averageLearningTime }} 分钟/天</div>
                <div class="mt-4 h-2 w-full rounded-full bg-muted">
                  <div class="h-2 rounded-full bg-primary" :style="{ width: averageLearningTimePercent + '%' }"></div>
                </div>
                <div class="mt-2 text-xs text-muted-foreground">{{ learningTimeChange }} 相比上周</div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader class="pb-2">
                <CardTitle class="text-sm font-medium">单词掌握率</CardTitle>
              </CardHeader>
              <CardContent>
                <div class="text-2xl font-bold">{{ wordMasteryRate }}%</div>
                <div class="mt-4 h-2 w-full rounded-full bg-muted">
                  <div class="h-2 rounded-full bg-primary" :style="{ width: wordMasteryRate + '%' }"></div>
                </div>
                <div class="mt-2 text-xs text-muted-foreground">{{ masteryRateChange }} 相比上周</div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader class="pb-2">
                <CardTitle class="text-sm font-medium">活跃用户比例</CardTitle>
              </CardHeader>
              <CardContent>
                <div class="text-2xl font-bold">{{ activeUserRate }}%</div>
                <div class="mt-4 h-2 w-full rounded-full bg-muted">
                  <div class="h-2 rounded-full bg-primary" :style="{ width: activeUserRate + '%' }"></div>
                </div>
                <div class="mt-2 text-xs text-muted-foreground">{{ activeUserChange }} 相比上周</div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="analytics" class="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>高级分析</CardTitle>
              <CardDescription>深入了解用户学习行为和模式</CardDescription>
            </CardHeader>
            <CardContent>
              <div class="h-[400px] flex items-center justify-center">
                <div class="text-sm text-muted-foreground">高级分析图表占位符</div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="activity" class="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>最近活动</CardTitle>
              <CardDescription>用户最近的学习活动和进度</CardDescription>
            </CardHeader>
            <CardContent>
              <div class="space-y-8">
                <div v-for="(activity, index) in recentActivities" :key="index" class="flex">
                  <div class="relative mr-4">
                    <div class="h-9 w-9 rounded-full bg-primary/10 flex items-center justify-center">
                      <BookOpen v-if="activity.type === 'word'" class="h-4 w-4 text-primary" />
                      <User v-else class="h-4 w-4 text-primary" />
                    </div>
                    <div class="absolute -bottom-0.5 -right-0.5 h-3 w-3 rounded-full border-2 border-background bg-green-500"></div>
                  </div>
                  <div class="space-y-1">
                    <p class="text-sm">
                      {{ activity.type === 'word' ? '学习了新单词' : '完成了测试' }}
                      <span class="font-medium">{{ activity.content }}</span>
                    </p>
                    <p class="text-sm text-muted-foreground">{{ activity.time }}</p>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, defineComponent, h } from 'vue'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle
} from '@/components/ui/card'
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger
} from '@/components/ui/tabs'
import { BarChart2, BookOpen, Users, User, Clock, GraduationCap, TrendingUp } from 'lucide-vue-next'

// 导入API模块
import statisticAPI from '@/api/statistic.js'
import userAPI from '@/api/user.js'
import wordAPI from '@/api/word.js'

// 仪表板卡片组件
const DashboardCard = defineComponent({
  props: {
    title: String,
    value: String,
    change: String,
    trend: {
      type: String,
      validator: (value) => ['up', 'down'].includes(value)
    },
    icon: Object
  },
  setup(props) {
    return () => h(Card, {}, {
      default: () => [
        h(CardHeader, { class: 'flex flex-row items-center justify-between space-y-0 pb-2' }, {
          default: () => [
            h(CardTitle, { class: 'text-sm font-medium' }, () => props.title),
            h(props.icon, { class: 'h-4 w-4 text-muted-foreground' })
          ]
        }),
        h(CardContent, {}, {
          default: () => [
            h('div', { class: 'text-2xl font-bold' }, props.value),
            h('div', { class: 'text-sm text-muted-foreground' }, [
              h(TrendingUp, {
                class: `mr-2 h-4 w-4 ${props.trend === 'up' ? 'text-green-500' : 'text-red-500'}`
              }),
              h('span', {}, props.change)
            ])
          ]
        })
      ]
    })
  }
})

// 响应式数据
const stats = ref([
  { id: 1, name: '总用户数', value: '0', icon: Users, change: '+0%', changeType: 'up' },
  { id: 2, name: '总单词数', value: '0', icon: BookOpen, change: '+0%', changeType: 'up' },
  { id: 3, name: '学习记录', value: '0', icon: GraduationCap, change: '+0%', changeType: 'up' },
  { id: 4, name: '反馈数量', value: '0', icon: BarChart2, change: '+0%', changeType: 'up' }
])

const recentUsers = ref([])
const popularWords = ref([])
const recentActivities = ref([])

// 统计数据
const quizCompletionRate = ref(0)
const quizCompletionChange = ref('+0%')
const averageLearningTime = ref(0)
const averageLearningTimePercent = ref(0)
const learningTimeChange = ref('+0%')
const wordMasteryRate = ref(0)
const masteryRateChange = ref('+0%')
const activeUserRate = ref(0)
const activeUserChange = ref('+0%')

const loading = ref(true)

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  const now = new Date()
  const diffTime = Math.abs(now - date)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays === 1) return '今天'
  if (diffDays === 2) return '昨天'
  return `${diffDays - 1} 天前`
}

// 获取统计数据
const fetchStats = async (period = 'all') => {
  loading.value = true

  try {
    const currentUserStats = await statisticAPI.getCurrentUserStatistics()
    if (currentUserStats.code === 200) {
      const data = currentUserStats.data

      // 更新统计数据
      quizCompletionRate.value = data.quizCompletionRate || 0
      quizCompletionChange.value = data.quizCompletionChange || '+0%'
      averageLearningTime.value = data.averageLearningTime || 0
      averageLearningTimePercent.value = data.averageLearningTimePercent || 0
      learningTimeChange.value = data.learningTimeChange || '+0%'
      wordMasteryRate.value = data.wordMasteryRate || 0
      masteryRateChange.value = data.masteryRateChange || '+0%'
      activeUserRate.value = data.activeUserRate || 0
      activeUserChange.value = data.activeUserChange || '+0%'
    }

    // 获取用户列表
    const usersResponse = await userAPI.getUsers()
    if (usersResponse.code === 200) {
      recentUsers.value = usersResponse.data.slice(0, 5)

      // 更新总用户数统计
      stats.value[0].value = usersResponse.data.length.toString()
      stats.value[0].change = `+${usersResponse.data.length > 0 ? '12.5' : '0'}%`
    }

    // 获取单词列表
    const wordsResponse = await wordAPI.getWords()
    if (wordsResponse.code === 200) {
      // 更新总单词数统计
      stats.value[1].value = wordsResponse.data.length.toString()
      stats.value[1].change = `+${wordsResponse.data.length > 0 ? '8.2' : '0'}%`

      // 获取热门单词
      popularWords.value = wordsResponse.data
          .map(word => ({
            id: word.id,
            word: word.word,
            reviewCount: word.reviewCount || Math.floor(Math.random() * 100) + 20,
            masteryRate: word.masteryRate || Math.floor(Math.random() * 40) + 60
          }))
          .sort((a, b) => b.reviewCount - a.reviewCount)
          .slice(0, 5)
    }

    // 模拟最近活动数据
    recentActivities.value = []

  } catch (error) {
    console.error('获取统计数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchStats()
})
</script>
